import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../models/server_config.dart';
import '../providers/vpn_provider.dart';
import '../services/subscription_service.dart';
import 'add_server_dialog.dart';

/// 服务器导入方式选择对话框
class ServerImportDialog extends StatelessWidget {
  const ServerImportDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
      ),
      child: Container(
        constraints: const BoxConstraints(maxWidth: 400),
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        Theme.of(context).colorScheme.primary,
                        Theme.of(context).colorScheme.primary.withOpacity(0.7),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Icon(
                    Icons.add_circle,
                    color: Colors.white,
                    size: 28,
                  ),
                ),
                const SizedBox(width: 16),
                const Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Add Server',
                        style: TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 4),
                      Text(
                        'Choose import method',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            
            // 导入方式选项
            _ImportMethodCard(
              icon: Icons.edit,
              title: 'Manual Input',
              subtitle: 'Fill in server details manually',
              color: Colors.blue,
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => const AddServerDialog(),
                );
              },
            ),
            const SizedBox(height: 12),
            
            _ImportMethodCard(
              icon: Icons.content_paste,
              title: 'Import from Clipboard',
              subtitle: 'Parse server link from clipboard',
              color: Colors.green,
              onTap: () async {
                Navigator.pop(context);
                await _importFromClipboard(context);
              },
            ),
            const SizedBox(height: 12),
            
            _ImportMethodCard(
              icon: Icons.qr_code_scanner,
              title: 'Scan QR Code',
              subtitle: 'Import by scanning QR code',
              color: Colors.purple,
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => const QrScanDialog(),
                );
              },
            ),
            const SizedBox(height: 12),
            
            _ImportMethodCard(
              icon: Icons.link,
              title: 'Import from URL',
              subtitle: 'Parse server configuration from URL',
              color: Colors.orange,
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => const ImportFromUrlDialog(),
                );
              },
            ),
            const SizedBox(height: 12),
            
            _ImportMethodCard(
              icon: Icons.file_upload,
              title: 'Import from File',
              subtitle: 'Import configuration file',
              color: Colors.teal,
              onTap: () {
                Navigator.pop(context);
                showDialog(
                  context: context,
                  builder: (context) => const ImportFromFileDialog(),
                );
              },
            ),
            const SizedBox(height: 20),
            
            Align(
              alignment: Alignment.centerRight,
              child: TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('Cancel'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _importFromClipboard(BuildContext context) async {
    try {
      final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
      final text = clipboardData?.text?.trim();
      
      if (text == null || text.isEmpty) {
        if (context.mounted) {
          _showErrorSnackBar(context, 'Clipboard is empty');
        }
        return;
      }

      final subscriptionService = SubscriptionService();
      final lines = text.split('\n');
      final servers = <ServerConfig>[];
      
      print('📋 Clipboard import: Processing ${lines.length} lines');
      
      for (var line in lines) {
        line = line.trim();
        if (line.isEmpty) continue;
        
        try {
          if (line.startsWith('vmess://')) {
            final server = subscriptionService.parseVMessLink(line);
            servers.add(server);
            print('✅ Parsed VMess: ${server.name}');
          } else if (line.startsWith('vless://')) {
            final server = subscriptionService.parseVLessLink(line);
            servers.add(server);
            print('✅ Parsed VLESS: ${server.name}');
          } else if (line.startsWith('trojan://')) {
            final server = subscriptionService.parseTrojanLink(line);
            servers.add(server);
            print('✅ Parsed Trojan: ${server.name}');
          } else if (line.startsWith('ss://')) {
            final server = subscriptionService.parseShadowsocksLink(line);
            servers.add(server);
            print('✅ Parsed Shadowsocks: ${server.name}');
          } else {
            if (line.length > 10) {
              print('⚠️ Unsupported protocol: ${line.substring(0, 20)}...');
            }
          }
        } catch (e) {
          print('❌ Failed to parse line: $e');
          print('   Line content: ${line.length > 50 ? line.substring(0, 50) + '...' : line}');
        }
      }

      if (servers.isEmpty) {
        if (context.mounted) {
          _showErrorSnackBar(context, 'No valid server links found in clipboard');
        }
        return;
      }

      if (context.mounted) {
        final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
        
        print('📥 Adding ${servers.length} servers to VPN provider...');
        for (var i = 0; i < servers.length; i++) {
          final server = servers[i];
          print('   [$i] Adding: ${server.name} (${server.protocol}://${server.address}:${server.port})');
          await vpnProvider.addServer(server);
        }
        print('✅ All servers added successfully');
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.check_circle, color: Colors.white),
                const SizedBox(width: 12),
                Text('Successfully imported ${servers.length} server${servers.length > 1 ? 's' : ''}'),
              ],
            ),
            backgroundColor: Colors.green,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    } catch (e) {
      if (context.mounted) {
        _showErrorSnackBar(context, 'Failed to import: $e');
      }
    }
  }

  void _showErrorSnackBar(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            const Icon(Icons.error, color: Colors.white),
            const SizedBox(width: 12),
            Expanded(child: Text(message)),
          ],
        ),
        backgroundColor: Colors.red,
        duration: const Duration(seconds: 4),
      ),
    );
  }
}

/// 导入方式卡片
class _ImportMethodCard extends StatelessWidget {
  final IconData icon;
  final String title;
  final String subtitle;
  final Color color;
  final VoidCallback onTap;

  const _ImportMethodCard({
    required this.icon,
    required this.title,
    required this.subtitle,
    required this.color,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: Theme.of(context).dividerColor.withOpacity(0.1),
        ),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Icon(icon, color: color, size: 24),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      subtitle,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ),
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: 16,
                color: Colors.grey.shade400,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// QR码扫描对话框
class QrScanDialog extends StatefulWidget {
  const QrScanDialog({super.key});

  @override
  State<QrScanDialog> createState() => _QrScanDialogState();
}

class _QrScanDialogState extends State<QrScanDialog> {
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.purple.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(Icons.qr_code_scanner, color: Colors.purple),
          ),
          const SizedBox(width: 12),
          const Text('Scan QR Code'),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 250,
            height: 250,
            decoration: BoxDecoration(
              color: Colors.black,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.purple, width: 2),
            ),
            child: const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.qr_code_scanner, size: 64, color: Colors.white54),
                  SizedBox(height: 16),
                  Text(
                    'Camera integration\ncoming soon',
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.white54),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue.shade700, size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Requires camera permission and qr_code_scanner package',
                    style: TextStyle(fontSize: 12, color: Colors.blue.shade700),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Close'),
        ),
      ],
    );
  }
}

/// 从URL导入对话框
class ImportFromUrlDialog extends StatefulWidget {
  const ImportFromUrlDialog({super.key});

  @override
  State<ImportFromUrlDialog> createState() => _ImportFromUrlDialogState();
}

class _ImportFromUrlDialogState extends State<ImportFromUrlDialog> {
  final _urlController = TextEditingController();
  bool _isLoading = false;

  @override
  void dispose() {
    _urlController.dispose();
    super.dispose();
  }

  Future<void> _importFromUrl() async {
    final url = _urlController.text.trim();
    if (url.isEmpty) {
      _showError('Please enter a URL');
      return;
    }

    setState(() => _isLoading = true);

    try {
      final subscriptionService = SubscriptionService();
      ServerConfig server;

      if (url.startsWith('vmess://')) {
        server = subscriptionService.parseVMessLink(url);
      } else if (url.startsWith('vless://')) {
        server = subscriptionService.parseVLessLink(url);
      } else if (url.startsWith('trojan://')) {
        server = subscriptionService.parseTrojanLink(url);
      } else if (url.startsWith('ss://')) {
        server = subscriptionService.parseShadowsocksLink(url);
      } else {
        _showError('Unsupported protocol. Supported: vmess://, vless://, trojan://, ss://');
        return;
      }

      if (mounted) {
        final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
        print('📥 URL Import: Adding server ${server.name} (${server.protocol}://${server.address}:${server.port})');
        await vpnProvider.addServer(server);
        print('✅ Server added successfully');

        if (mounted) {
          Navigator.pop(context);
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Row(
                children: [
                  Icon(Icons.check_circle, color: Colors.white),
                  SizedBox(width: 12),
                  Text('Server imported successfully'),
                ],
              ),
              backgroundColor: Colors.green,
            ),
          );
        }
      }
    } catch (e) {
      _showError('Failed to import: $e');
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  void _showError(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const Icon(Icons.error, color: Colors.white),
              const SizedBox(width: 12),
              Expanded(child: Text(message)),
            ],
          ),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.orange.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(Icons.link, color: Colors.orange),
          ),
          const SizedBox(width: 12),
          const Text('Import from URL'),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'Paste a server configuration URL',
            style: TextStyle(fontSize: 14, color: Colors.grey),
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _urlController,
            decoration: InputDecoration(
              hintText: 'vmess://... or vless://... or trojan://...',
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              prefixIcon: const Icon(Icons.link),
              suffixIcon: IconButton(
                icon: const Icon(Icons.content_paste),
                onPressed: () async {
                  final data = await Clipboard.getData(Clipboard.kTextPlain);
                  if (data?.text != null) {
                    _urlController.text = data!.text!;
                  }
                },
                tooltip: 'Paste from clipboard',
              ),
            ),
            maxLines: 3,
            minLines: 1,
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue.shade700, size: 18),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Supported: VMess, VLESS, Trojan, Shadowsocks',
                    style: TextStyle(fontSize: 11, color: Colors.blue.shade700),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: _isLoading ? null : () => Navigator.pop(context),
          child: const Text('Cancel'),
        ),
        ElevatedButton.icon(
          onPressed: _isLoading ? null : _importFromUrl,
          icon: _isLoading
              ? const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Icon(Icons.download),
          label: Text(_isLoading ? 'Importing...' : 'Import'),
        ),
      ],
    );
  }
}

/// 从文件导入对话框
class ImportFromFileDialog extends StatelessWidget {
  const ImportFromFileDialog({super.key});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Row(
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.teal.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: const Icon(Icons.file_upload, color: Colors.teal),
          ),
          const SizedBox(width: 12),
          const Text('Import from File'),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.teal, width: 2, style: BorderStyle.solid),
              borderRadius: BorderRadius.circular(12),
              color: Colors.teal.withOpacity(0.05),
            ),
            child: Column(
              children: [
                Icon(Icons.upload_file, size: 48, color: Colors.teal.shade300),
                const SizedBox(height: 12),
                Text(
                  'Click to select file',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.teal.shade700,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Supported: JSON, TXT',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.blue.shade50,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(Icons.info_outline, color: Colors.blue.shade700, size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    'Requires file_picker package to select files',
                    style: TextStyle(fontSize: 12, color: Colors.blue.shade700),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Close'),
        ),
      ],
    );
  }
}
